package net.xxcl.exam.controller;

import jxl.Workbook;
import jxl.write.Label;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;
import net.xxcl.exam.model.StuForDelayTime;
import net.xxcl.exam.model.StuForMark;
import net.xxcl.exam.pojo.Criteria;
import net.xxcl.exam.pojo.Question;
import net.xxcl.exam.pojo.Score;
import net.xxcl.exam.service.ScoreService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * User: 夏汛
 * Date: 11-12-28
 * Time: 下午7:37
 */
@Controller
@RequestMapping("/score")
public class ScoreController {
    @Autowired
    private ScoreService scoreService;

    /**
     * 获取考试延迟界面列表
     * @param start
     * @param limit
     * @param paperid
     * @param kemuid
     * @param cardid
     * @param username
     * @param number
     * @return
     */
    @RequestMapping(value = "/getDelayTimeUI",method= RequestMethod.POST)
     public @ResponseBody Map<String,Object> getKemus(@RequestParam("start") Integer start,
                                                      @RequestParam("limit") Integer limit,
                                                      @RequestParam(value = "paperid",required = false) Integer paperid,
                                                      @RequestParam(value = "kemuid",required = false) Integer kemuid,
                                                      @RequestParam(value = "cardid",required = false) String cardid,
                                                      @RequestParam(value = "username",required = false) String username,
                                                      @RequestParam(value = "number",required = false) String number){
        Map<String,Object> responseMap = new HashMap<String, Object>();
        Criteria criteria = new Criteria();
        //加上查询条件
        if(!(cardid==null || cardid.equals(""))) criteria.put("cardid","%"+cardid+"%");
        if(!(number==null || number.equals(""))) criteria.put("number","%"+number+"%");
        if(!(username==null || username.equals(""))) criteria.put("username","%"+username+"%");
        if(paperid!=null) criteria.put("paperid",paperid);
        if(kemuid!=null) criteria.put("kemuid",kemuid);

        criteria.setMysqlOffset(start);
        criteria.setMysqlLength(limit);
        criteria.setOrderByClause("t_paper.id desc");
        int total = scoreService.countForDelayTime(criteria);
        List<StuForDelayTime> list = scoreService.getForDelayTime(criteria);
        responseMap.put("total",total);
        responseMap.put("rows",list);
        return responseMap;
    }

    /**
     * 设置延时
     * @param paperid
     * @param stuid
     * @param delaytime
     * @return
     */
    @RequestMapping(value = "/setDelayTime",method= RequestMethod.POST)
    public @ResponseBody Map<String,Object> setDelayTime(@RequestParam("paperid") Integer paperid,
                                                     @RequestParam("stuid") Integer stuid,
                                                     @RequestParam("delaytime") Integer delaytime){
        Map<String,Object> responseMap = new HashMap<String, Object>();
        try{
            Score score = new Score();
            score.setPaperid(paperid);
            score.setStuid(stuid);
            score.setDelaytime(delaytime);
            scoreService.updateByPrimaryKeySelective(score);
            responseMap.put("info","设置延时"+delaytime+"分钟");
        } catch (Exception e){
            e.printStackTrace();
            responseMap.put("info","设置延时失败，请重试！");
        }
        return responseMap;
    }

    /**
     * 计算客观题成绩
     * @param id
     * @return
     */
    @RequestMapping(value = "/countMark")
    public @ResponseBody Map<String,Object> countMark(@RequestParam("id") Integer id){
        Map<String,Object> responseMap = new HashMap<String, Object>();
        try{
            List<Question> questions = scoreService.getPaperRightAnswer(id);
            List<Score> scores = scoreService.selectByPaperId(id);
            for(Score score:scores){
                //客观题总成绩
                int totalKgtMark = 0;
                //获取某位考生的答案
                String stuAnswer = score.getKgtda();
                //操作题不会自动保存，无答案，只计算客观题
                if(stuAnswer!=null){
                    //用subString去掉最开始的[和最末尾的]
                    stuAnswer = stuAnswer.substring(1,stuAnswer.length()-1).replace("{","").replace("}","").replace("\"","");
                    String[] str = stuAnswer.split(":");
                    for (int h=1;h<str.length;h+=2){
                        //取出question的id号码
                        int questionId = Integer.parseInt(str[h].substring(0,str[h].indexOf(",")));
                        String answerStr = "";
                        //取出answer的字符串,如果满足(h+2)==str.length，表示是最后一答案了，不用lastIndexOf(",")
                        if((h+2)==str.length){
                            answerStr = str[h+1];
                        } else {
                            answerStr = str[h+1].substring(0,str[h+1].lastIndexOf(","));
                        }
                        for(Question question:questions){
                            if(question.getId()==questionId){
                                String[] oneAnswer = answerStr.split(",");
                                //如果题目数量都不对，肯定错了
                                if(question.getAnswers().size()==oneAnswer.length){
                                    List<Integer> a = new ArrayList<Integer>();
                                    List<Integer> b = new ArrayList<Integer>();
                                    for(int i=0;i<oneAnswer.length;i++){
                                        a.add(question.getAnswers().get(i).getId());
                                        b.add(Integer.parseInt(oneAnswer[i]));
                                    }
                                    //先排序
                                    Collections.sort(a);
                                    Collections.sort(b);
                                    Boolean flag = true;
                                    for(int i=0;i<oneAnswer.length;i++){
                                        if(a.get(i)!=Integer.parseInt(oneAnswer[i])){
                                            flag = false;
                                            break;
                                        }
                                    }
                                    if(flag){
                                        totalKgtMark += question.getMark();
                                    }
                                }
                                break;
                            }
                        }
                    }
                }
                Score updateScore = new Score();
                updateScore.setPaperid(score.getPaperid());
                updateScore.setStuid(score.getStuid());
                updateScore.setKgtmark(totalKgtMark);
                scoreService.updateByPrimaryKeySelective(updateScore);
            }
        } catch (Exception e){
            e.printStackTrace();
            responseMap.put("info",e.getMessage());
        }
        return responseMap;
    }

    /**
     * 显示成绩列表
     * @param start
     * @param limit
     * @param paperid
     * @param username
     * @param classids
     * @return
     */
    @RequestMapping(value = "/getMarkUI",method= RequestMethod.POST)
    public @ResponseBody Map<String,Object> getMarkUI(@RequestParam("start") Integer start,
                                                     @RequestParam("limit") Integer limit,
                                                     @RequestParam(value = "paperid",required = false) Integer paperid,
                                                     @RequestParam(value = "username",required = false) String username,
                                                     @RequestParam(value = "classids",required = false) String classids){
        Map<String,Object> responseMap = new HashMap<String, Object>();System.out.println(username);
        Criteria criteria = new Criteria();
        //加上查询条件
        if(!(paperid==null || paperid.equals(""))) criteria.put("paperid",paperid);
        if(!(username==null || username.equals(""))) criteria.put("username","%"+username+"%");
        if(!(classids==null || classids.equals(""))){
            String[] str = classids.split(",");
            List<String> classList = new ArrayList<String>();
            for(String s:str){
                classList.add(s);
            }
            criteria.put("classids",classList);
        }
        int total = scoreService.countByExample(criteria);
        criteria.setMysqlOffset(start);
        criteria.setMysqlLength(limit);
        List<StuForMark> list = scoreService.selectForMark(criteria);
        responseMap.put("total",total);
        responseMap.put("rows",list);
        return responseMap;
    }

    /**
     * 导出成绩
     * @param paperid
     * @param username
     * @param classids
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/exportMark",method= RequestMethod.POST)
    public @ResponseBody Map<String,Object> exportMark(
                                                      @RequestParam(value = "paperid",required = false) Integer paperid,
                                                      @RequestParam(value = "username",required = false) String username,
                                                      @RequestParam(value = "classids",required = false) String classids,
                                                      HttpServletRequest request,HttpServletResponse response){
        Map<String,Object> responseMap = new HashMap<String, Object>();System.out.println(username);
        Criteria criteria = new Criteria();
        //加上查询条件
        if(!(paperid==null || paperid.equals(""))) criteria.put("paperid",paperid);
        if(!(username==null || username.equals(""))) criteria.put("username","%"+username+"%");
        if(!(classids==null || classids.equals(""))){
            String[] str = classids.split(",");
            List<String> classList = new ArrayList<String>();
            for(String s:str){
                classList.add(s);
            }
            criteria.put("classids",classList);
        }
        int total = scoreService.countByExample(criteria);
        List<StuForMark> list = scoreService.selectForMark(criteria);
        try{
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss");
            String fileName = UUID.randomUUID()+".xls";
            String filePath = request.getSession().getServletContext().getRealPath("temp");
            File dirPath = new File(filePath);
            if (!dirPath.exists()) {
                dirPath.mkdirs();
            }
            WritableWorkbook book  =  Workbook.createWorkbook(new File(filePath+"\\"+fileName));
            WritableSheet sheet  =  book.createSheet( "办公自动化成绩",  0 );
            sheet.addCell(new  Label( 0,  0,  "身份证" ));
            sheet.addCell(new  Label( 1,  0,  "学号" ));
            sheet.addCell(new  Label( 2,  0,  "姓名" ));
            sheet.addCell(new  Label( 3,  0,  "班级" ));
            sheet.addCell(new  Label( 4,  0,  "电话号码" ));
            sheet.addCell(new  Label( 5,  0,  "试卷" ));
            sheet.addCell(new  Label( 6,  0,  "科目" ));
            sheet.addCell(new  Label( 7,  0,  "客观题成绩" ));
            sheet.addCell(new  Label( 8,  0,  "考试状态" ));
            sheet.addCell(new  Label( 9,  0,  "开始考试时间" ));
            for(int i=0;i<list.size();i++){
                StuForMark stuForMark = list.get(i);
                if(stuForMark.getCardid()!=null){
                    sheet.addCell(new  Label( 0, i+1, stuForMark.getCardid()));
                }
                if(stuForMark.getNumber()!=null){
                    sheet.addCell(new  Label( 1, i+1, stuForMark.getNumber()));
                }
                if(stuForMark.getUsername()!=null){
                    sheet.addCell(new  Label( 2, i+1, stuForMark.getUsername()));
                }
                if(stuForMark.getClassname()!=null){
                    sheet.addCell(new  Label( 3,  i+1, stuForMark.getClassname()));
                }
                if(stuForMark.getPhone()!=null){
                    sheet.addCell(new  Label( 4, i+1, stuForMark.getPhone()));
                }
                if(stuForMark.getPapername()!=null){
                    sheet.addCell(new  Label( 5, i+1, stuForMark.getPapername()));
                }
                if(stuForMark.getKemuname()!=null){
                    sheet.addCell(new  Label( 6, i+1, stuForMark.getKemuname()));
                }
                sheet.addCell(new  jxl.write.Number(7, i+1,  stuForMark.getKgtmark()));
                String state = "";
                if(stuForMark.getState()==0){
                    state = "缺考";
                }
                if(stuForMark.getCardid()!=null){
                    sheet.addCell(new  Label( 8,  i+1, state));
                }
                if(stuForMark.getFirststarttime()!=null){
                    sheet.addCell(new  Label( 9,  i+1, sdf.format(stuForMark.getFirststarttime())));
                }
            }
            book.write();
            book.close();
            responseMap.put("path","temp/"+fileName);
        } catch (Exception e){
            e.printStackTrace();
            responseMap.put("info","导出失败！");
        }
        return responseMap;
    }
}
